package com.tensquare.friend.controller;

import com.tensquare.common.entity.Result;
import com.tensquare.common.entity.StatusCode;
import com.tensquare.friend.service.FriendService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author fangyu
 * @version v1.0.0
 * @date 2020/10/15 4:23 下午
 */
@RestController
@RequestMapping("/friend")
public class FriendController {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private FriendService friendService;

    /**
     * 添加好友
     * @param friendid
     * @param type
     * @return
     */
    @RequestMapping("/like/{friendid}/{type}")
    public Result addFriend(@PathVariable String friendid, @PathVariable String type) {
        Claims claims = (Claims) request.getAttribute("user_claims");
        if (claims == null) {
            return new Result(false, StatusCode.OK, "无权访问");
        }
        // 如果是喜欢
        if ("1".equals(type)) {
            if (friendService.addFriend(claims.getId(), friendid) > 0) {
                return new Result(true, StatusCode.OK, "喜欢朋友成功");
            } else {
                return new Result(false, StatusCode.OK, "已经添加此好友");
            }

        } else {
            // 向不喜欢列表中添加记录
            friendService.addNoFriend(claims.getId(),friendid);
        }
        return new Result(true, StatusCode.OK, "操作成功");
    }

    /**
     * 删除好友
     * @param friendid
     * @return
     */
    @RequestMapping(value="/{friendid}",method= RequestMethod.DELETE)
    public Result remove(@PathVariable String friendid) {
        Claims claims=(Claims)request.getAttribute("user_claims");
        if (claims == null) {
            return new Result(false, StatusCode.ACCESS_ERROR,"无权访问");
        }
        friendService.deleteFriend(claims.getId(), friendid);
        return new Result(true, StatusCode.OK, "删除成功");
    }
}
